package com.ggh.handler;
import java.util.*;

import com.ggh.entity.RoomBeanP;
import com.ggh.entity.TypeBean;
import com.ggh.entity.UserBean;
import com.ggh.util.JsonUtils;
import com.ggh.vo.UserToken;
import com.ggh.websocket.PK_WebSocket_P;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jj
 * @date 2019/10/23 9:40
 * 机器人下注
 */
@Component
public class AiHandler {
    /**
     * 动作类
     */
   private UserOperationP userOperationP=new UserOperationP();
    /**
     * 随机数
     */
    Random rand = new Random();
    /**
     * 解析类
     */
    Gson gson=JsonUtils.get();
    /**
     * 判断四人还是百人和
     * 相关属性进入不同的方法
     * @param room
     * @param user
     * @param type
     * @return
     */
    public boolean judge(RoomBeanP room, UserBean user,Integer type){

        switch (type){
            case 1:
                /*判断是否可以上庄*/
                if (user.getIsKamisho()){
                    return false;
                }
                return room.getGame_type()<2 ? kaMiShoSr(room,user):kaMiShoBr(room, user);
            case 2:
                //下庄，只有百人
                return shimoSho(room,user);
            case 3:
                //下注
                return room.getGame_type()>2 ? actionSr(room,user):actionBr(room, user);
            default:
                return false;
        }
    }
    /**
    * @description :四人抢庄
    * @param room
    * @param user
    * @date : 2019/10/24 9:23
    * @author : jj
    */
    protected boolean kaMiShoSr(RoomBeanP room,UserBean user){
        int ambiguity= (int) (Math.random()* 2);
        if (ambiguity==1){
            user.getLock().lock();
            int i=0;
            try {
                i = userOperationP.robBanker(user, room);
                if (i==1){
                    sendMessageAll(UserToken.newInstance(user.getUserid(),"SiRenGameInciDent",gson.toJson(room), TypeBean.SUCCESS),room);
                }
            }catch (Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            }finally {
                user.getLock().unlock();
            }
            return i==1?true:false;
        }
        return false;
    }

    /**
     * 百人抢庄
     * @param room
     * @param user
     * @return
     */
    protected boolean kaMiShoBr(RoomBeanP room, UserBean user) {
        int aika=room.getGame_number()%user.getIsKaMiShoBr();
        if (aika==0){
            user.getLock().lock();
            int i=0;
            try {
                i = userOperationP.robBanker(user, room);
                if (i==1){
                    sendMessageAll(UserToken.newInstance(user.getUserid(),"BaiRenShangZhuangSuccess",gson.toJson(room), TypeBean.SUCCESS),room);
                }
            }catch (Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            }finally {
                user.getLock().unlock();
            }
            return i==1?true:false;
        }
        return false;
    }

    /**
     * 百人下庄,下庄不固定
     * @param room
     * @param user
     * @return
     */
    protected boolean shimoSho(RoomBeanP room, UserBean user){
        int aika=room.getGame_number()%user.getShimoShoBr();
        if (aika==0){
            userOperationP.downBanker(user, room);
            sendMessageAll(UserToken.newInstance(user.getUserid(),"BaiRenXiaZhuangSuccess",gson.toJson(room), TypeBean.SUCCESS),room);
            return true;
        }
        return false;
    }

    /**
     * 四人下注
     * @param room
     * @param user
     * @return
     */
    protected boolean actionSr(RoomBeanP room,UserBean user){
        //运算每个下注结果
        int bottom = actionRSA(user.getSection());
        int result=bottom*room.getFen()/100/3;
        user.getLock().lock();
        try {
            user.setFirst(result);
            user.setSecond(result);
            user.setThird(result);
            user.setPower_type(1);
            sendMessageAll(UserToken.newInstance(user.getUserid(),"SiRenGameInciDent",gson.toJson(room), TypeBean.SUCCESS),room);
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }finally {
            user.getLock().unlock();
        }
        return false;
    }

    /**
     * 百人下注
     * @param room
     * @param user
     * @return
     */
    private boolean actionBr(RoomBeanP room,UserBean user){
        return actionRSA(room,user);
    }

    /**
     * 下注算法
     * @param section
     * @return
     */
    private int  actionRSA(String section){
        String[] sections = section.split("-");
        String section1 = sections[0];
        String section2 = sections[1];
        int bottom=rand.nextInt((Integer.valueOf(section2)+1-Integer.valueOf(section1)))+Integer.valueOf(section2);
        return bottom;
    }
    /**
     * 百人下注算法
     * @param room
     * @return
     */
    private boolean  actionRSA(RoomBeanP room,UserBean user){
        HashMap map=new HashMap();
        //
        int bottom = actionRSA(user.getSection());
       //如果没人下注的情况
        int result=0;
        System.out.println(room.getKMoney()+"##################################");
        if (room.getKMoney()<500){
            return false;
        }
        if (room.getKMoney()==room.getZMoney()){
            //下注结果
             result=bottom*room.getKMoney()/1200/(rand.nextInt(10)+1);
            int random=rand.nextInt(3)+1;
            if (room.getKMoney()-result<0){
                return false;
            }
            int betArea = bet(user, random, result,room);
            /*下注成功*/
            boolean b = sendAllorRoom(betArea, room, map, result, user);
            if (b){
                return true;
            }
        }
        //没下完
        if (room.getKMoney()<room.getZMoney()&&room.getKMoney()>0){
            //设置下注区间*可下注/1~5
            result=bottom*room.getKMoney()/1200/(rand.nextInt(5)+1);
            if (room.getKMoney()-result<0){
                return false;
            }

            if (room.getGame_type()==1){
                /*下注最多的位置 设置下注区间*可下注/1~5*2/3*/
                int betArea = betBrx(user, result * 1 / 3, room);
                boolean b = sendAllorRoom(betArea, room, map, result, user);
                if (b){
                    /*随机下注设置下注区间*可下注/1~5/3*/
                    int random=rand.nextInt(3)+1;
                    System.out.println("@@@@@@@@@@"+random);
                    int betArea1 = bet(user, random, result *2/ 3, room);
                    boolean bl = sendAllorRoom(betArea1, room, map, result, user);
                    if (bl){
                        return true;
                    }
                }
            }else {
                int betArea = betBra(user, result, room);
                boolean b = sendAllorRoom(betArea, room, map, result, user);
            }

        }

        return true;
    }
    /**
     * @description :第一轮统一下注
     * @param user
     * @param random
     * @param result
     * @date : 2019/10/25 9:50
     * @author : jj
     */
    private int bet(UserBean user,int random,int result,RoomBeanP room){
        int betArea=0;
        switch (random){
            case 1:
                user.setChu(result);
                room.setChuMoney(room.getChuMoney() + result);
                betArea=1;
                break;
            case 2:
                user.setTian(result);
                room.setTianMoney(result);
                betArea=2;
                break;
            case 3:
                user.setMo(result);
                room.setMoMoney(result);
                betArea=3;
                break;
            default:
                System.out.println("参数错误！");
                return betArea;
        }
        return betArea;
    }
    /**
    * @description :百人大下注，第二轮以后
    * @param user
    * @param result 
    * @param room
    * @date : 2019/10/24 16:37
    * @author : jj
    */
    private int betBra(UserBean user,int result,RoomBeanP room){
        int betArea=0;
        if (user.getChu()>0){
            user.setChu(result);
            room.setChuMoney(room.getChuMoney() + result);
            betArea=1;
        }else if (user.getTian()>0){
            user.setTian(result);
            room.setTianMoney(result);
            betArea=2;
        }else if (user.getMo()>0) {
            user.setMo(result);
            room.setMoMoney(result);
            betArea=3;
        }
        return betArea;
    }
    /**
    * @description :第二轮下注百人小
    * @param user 
    * @param result 
    * @param room
    * @date : 2019/10/25 10:46
    * @author : jj
    */
    private int betBrx(UserBean user,int result,RoomBeanP room){
        int betArea=0;
          if (user.getChu()>user.getTian()&&user.getChu()>user.getMo()){
              user.setChu(result);
              room.setChuMoney(room.getChuMoney() + result);
              betArea=1;
          }
          if (user.getTian()>user.getChu()&&user.getTian()>user.getMo()){
              user.setTian(result);
              room.setTianMoney(result);
              betArea=2;
          }
          if (user.getMo()>user.getTian()&&user.getMo()>user.getChu()){
              user.setMo(result);
              room.setMoMoney(result);
              betArea=3;
          }
        return betArea;
    }

    /**
    * @description :百人下注消息
    * @param betArea 
    * @param room 
    * @param map 
    * @param result 
    * @param user
    * @date : 2019/10/25 11:40
    * @author : jj
    */
    private  boolean sendAllorRoom(int betArea,RoomBeanP room, HashMap map,int result,UserBean user){
        map.clear();
        if (betArea>0){
            room.setKMoney(room.getKMoney()-result);
            String deskno="";
            List<Integer> list=null;
            switch (betArea){
                case 1:
                    deskno="Chu";
                    list = goldHandle(room.getCuserListMoney(), result);
                    break;
                case 2:
                    deskno="Tian";
                    list = goldHandle(room.getTuserListMoney(),result);
                    break;
                case 3:
                    deskno="Mo";
                    list = goldHandle(room.getMuserListMoney(),result);
                    break;
                default:
                    deskno = "" ;
                    break;
            }
            map.put("deskno", deskno);
            map.put("userid", user.getUserid());
            map.put("money", list);
            sendMessageAll(UserToken.newInstance(user.getUserid(),"BaiRenMoneyAIBetsSuccess",map, TypeBean.SUCCESS),room);

            return true;
        }
        return false;
    }
    /**
     * 相关金币分成金币组
     * @param mnyList
     * @param result
     */
    private List<Integer>  goldHandle(List<Integer> mnyList ,int result){
        int residues;
        int residue=0;
        int number =0;
        Integer[] integerArray = {500,100, 50, 20, 10,1};
        List<Integer> rtlist=new ArrayList<> ();
        List<Integer> list = new ArrayList<>(Arrays.asList(integerArray));
        for (Integer mt:list){
            if (result>=mt){
                residue=result%mt;
                if (residue==0){
                    number =result/mt;
                    result=0;
                }else {
                    residues=result-residue;
                    result=residue;
                    number = residues/mt;
                }
                System.out.println(result);
                for (int i=0;i<number ;i++){
                    mnyList.add(mt);
                    rtlist.add(mt);
                }
                if (result==0){
                    break;
                }
            }
        }
        for (int i=0;i<rtlist.size();i++){
            int n=rand.nextInt(rtlist.size());
            int m=rand.nextInt(rtlist.size());
            Collections.swap(rtlist,n,m);
        }
        return rtlist;
    }
    /**
     * @author : jj
     * @date : 2019/10/5 10:55
     * @description :发送消息给除去AI以外的所有人
     * @param rb
     * @return: void
     * @throws
     */
    public synchronized void sendMessageAll(UserToken userToken, RoomBeanP rb) {
        for (UserBean userb : rb.getGame_userlist()) {
            PK_WebSocket_P webSocket = Public_State_P.clients.get(String.valueOf(userb.getUserid()));
            if (webSocket != null && webSocket.getSession().isOpen() && userb.getExit_state() == 0&&userb.getIsAi()!=1) {
                // 不等于自己的则发送消息
                webSocket.sendMessageAiTo(userToken, userb);
            } else {
                continue;
            }
        }
    }

}
